package com.gjun.struts.resource.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gjun.struts.bean.ext.Order;
import com.gjun.struts.resource.dao.IOrderDao;

public class OrderDaoImpl extends HibernateDaoSupport  implements IOrderDao {

	public void saveOrder(Order order) {
		Session session = this.getHibernateTemplate().getSessionFactory().openSession();
		session.beginTransaction();
		order.setStatus(0);
		order.setOrderTime(0);
		order.setTotalPrice(0);
		session.save(order);
		session.getTransaction().commit();
		session.close();
		
	}

	public List<Order> getOrder(String conditions,String email) {
		// TODO Auto-generated method stub
		Session session = this.getHibernateTemplate().getSessionFactory().openSession();
		String hql = "select o from Order o";
		if(conditions != null){
			hql += " where "+conditions;
		}
		if(!email.isEmpty()){
			hql += " and o.userId in (select u.id from User u where u.email='"+email+"')";
		}
		List<Order> orders = session.createQuery(hql).list();
		session.close();
		return orders;
	}

	public void updateOrder(Order order) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().update(order);
		
	}

	public List<Order> getOrder(String conditions, String email, int start,
			int pageSize) {
		// TODO Auto-generated method stub
		Session session = this.getHibernateTemplate().getSessionFactory().openSession();
		String hql = "select o from Order o";
		if(conditions != null){
			hql += " where "+conditions;
		}
		if(email == null){
			hql += " and o.userId in (select u.id from User u where u.email='"+email+"')";
		}
		session.beginTransaction();
		Query query =  session.createQuery(hql);
		query.setFirstResult(start);
		query.setMaxResults(pageSize);
		List<Order> orders = query.list();
		session.close();
		return orders;
	}

	public Order getOrderById(int id) {
		// TODO Auto-generated method stub
		
		return (Order)this.getHibernateTemplate().get(Order.class, id);
	}

}
